<template>
  <div class="container">
    <div class="add-form">
      <el-collapse v-model="activeNames">
        <el-collapse-item name="1">
          <h1 slot="title">企业信息</h1>
          <el-form
            :disabled="isCheck"
            ref="company-info"
            :model="addForm"
            :rules="$rules"
            label-width="11rem"
            status-icon
            class="company-info-form grid-flex"
          >
            <el-form-item
              :label="$language.local('customerName')"
              prop="customerName"
            >
              <xy-input v-model="addForm.customerName" clearable></xy-input>
            </el-form-item>
            <el-form-item :label="$language.local('AgentId')" prop="AgentId">
              <el-select
                v-model="addForm.AgentId"
                clearable
                filterable
                :placeholder="
                  $language.local('请选择') + $language.local('AgentId')
                "
              >
                <el-option
                  v-for="item in agents"
                  :key="item.Id"
                  :label="item.AgentName"
                  :value="item.Id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              :label="$language.local('customTaxIdcd')"
              prop="customTaxIdcd"
            >
              <xy-input v-model="addForm.customTaxIdcd" clearable></xy-input>
            </el-form-item>
            <el-form-item
              :label="$language.local('customerManager')"
              prop="customerManager"
            >
              <select-name
                v-if="addForm.AgentId"
                v-model="addForm.customerManager"
                label-key="real_name"
                :apiName="`/api/Common/GetUserList?roleType=5&customerId=${addForm.AgentId}`"
              ></select-name>
              <xy-input v-else disabled></xy-input>
            </el-form-item>
            <el-form-item
              :label="$language.local('customLegalPerson')"
              prop="customLegalPerson"
            >
              <xy-input
                v-model="addForm.customLegalPerson"
                clearable
              ></xy-input>
            </el-form-item>
            <el-form-item :label="$language.local('IdNumber')" prop="IdNumber">
              <xy-input v-model="addForm.IdNumber" clearable></xy-input>
            </el-form-item>

            <el-form-item
              :label="$language.local('customCollector')"
              prop="customCollector"
            >
              <xy-input v-model="addForm.customCollector" clearable></xy-input>
            </el-form-item>
            <el-form-item
              :label="$language.local('customCollectorPhone')"
              prop="customCollectorPhone"
            >
              <xy-number
                v-model="addForm.customCollectorPhone"
                placeholder="此项为该企业的登录用户名"
                pr
                clearable
              ></xy-number>
            </el-form-item>
            <el-form-item
              :label="$language.local('customMail')"
              prop="customMail"
            >
              <xy-input v-model="addForm.customMail" clearable></xy-input>
            </el-form-item>
            <el-form-item :label="$language.local('areaName')" prop="areaName">
              <xy-input v-model="addForm.areaName" clearable></xy-input>
            </el-form-item>
          </el-form>
        </el-collapse-item>
        <el-collapse-item name="2">
          <h1 slot="title">开票信息</h1>
          <el-form
            :disabled="isCheck"
            ref="selectForm"
            :model="addForm"
            :rules="$rules"
            status-icon
            label-width="11rem"
            size="medium"
            class="grid-flex"
          >
            <el-form-item
              prop="invoiceType"
              :label="$language.local('开票类型')"
            >
              <el-radio-group v-model="addForm.invoiceType">
                <el-radio-button :label="1">全额</el-radio-button>
                <el-radio-button :label="2">差额</el-radio-button>
                <el-radio-button :label="3">其它</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              prop="Companytype"
              :label="$language.local('企业类型')"
            >
              <!-- <merchant-type v-model="addForm.Companytype"></merchant-type> -->
              <el-radio-group v-model="addForm.Companytype">
                <el-radio-button :label="1">企业</el-radio-button>
                <el-radio-button :label="2">个体工商户</el-radio-button>
              </el-radio-group>
            </el-form-item>

            <el-form-item prop="nsrxz" :label="$language.local('纳税人性质')">
              <el-radio-group v-model="addForm.nsrxz">
                <el-radio-button :label="1">一般纳税人</el-radio-button>
                <el-radio-button :label="2">小规模纳税人</el-radio-button>
              </el-radio-group>
            </el-form-item>

            <el-form-item
              prop="IsSendMessageToEmp"
              :label="$language.local('是否下发短信')"
            >
              <el-radio-group v-model="addForm.IsSendMessageToEmp">
                <el-radio-button :label="0">是</el-radio-button>
                <el-radio-button :label="1">否</el-radio-button>
              </el-radio-group>
            </el-form-item>

            <el-form-item
              prop="empSignType"
              :label="$language.local('自由职业者签约类型')"
            >
              <el-radio-group v-model="addForm.empSignType">
                <el-radio-button :label="1"
                  >先签约,后付款(电子协议)</el-radio-button
                >
                <el-radio-button :label="2">批量签约(纸质协议)</el-radio-button>
              </el-radio-group>
            </el-form-item>

            <el-form-item prop="payType" :label="$language.local('付款方式')">
              <el-radio-group v-model="addForm.payType">
                <el-radio-button :label="1">银行卡</el-radio-button>
                <el-radio-button :label="2">钱包账户</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <template v-if="addForm.payType == 2">
              <el-form-item prop="Account" :label="$language.local('钱包账号')">
                <xy-input v-model="addForm.Account"></xy-input>
              </el-form-item>
            </template>
            <template v-else>
              <template v-for="(item, index) in addForm.backcard">
                <el-form-item
                  :key="item.Id"
                  :prop="'backcard.' + index + '.AccountBank'"
                  :label="$language.local('AccountBank')"
                  :rules="$rules.AccountBank"
                >
                  <el-select
                    v-model="item.AccountBank"
                    clearable
                    filterable
                    :placeholder="
                      $language.local('此处输入关键字可以搜索') +
                      $language.local('开户行')
                    "
                  >
                    <el-option
                      v-for="item in banks"
                      :key="item.Id"
                      :label="item.BANKNAME"
                      :value="item.BANKNAME"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item
                  :key="index"
                  :prop="`backcard[${index}].BankNo`"
                  :rules="$rules.AccountBank"
                  :label="$language.local('BankNo')"
                >
                  <xy-number v-model="item.BankNo"></xy-number>
                </el-form-item>
              </template>
            </template>
          </el-form>
        </el-collapse-item>
        <el-collapse-item name="3">
          <h1 slot="title">项目名称</h1>

          <el-form
            :disabled="isCheck"
            :model="addForm"
            :rules="$rules"
            label-width="11rem"
            ref="taskInfoRef"
            status-icon
            class="pl-2"
          >
            <el-form-item
              :label="$language.local('项目名称')"
              prop="ProjectName"
            >
              <xy-input v-model="addForm.ProjectName" clearable></xy-input>
            </el-form-item>

            <el-form-item
              prop="RequirementDescription"
              :label="$language.local('RequirementDescription')"
            >
              <xy-input
                type="textarea"
                v-model="addForm.RequirementDescription"
                clearable
              ></xy-input>
              <div class="tips">
                1、工作内容的描述不能有如下字眼：<em class="red"
                  >工资、补贴、津贴、福利、劳务、销售、经纪、工程安装、装修、装饰、清包工</em
                >
                等字眼；
              </div>
              <div class="tips">
                2、工作内容描述不录入具体人员姓名、金额数字等详细内容；
              </div>
            </el-form-item>
            <!-- #region 灵工要求 -->
            <el-form-item
              prop="TechnicalRequirement"
              :label="$language.local('TechnicalRequirement')"
            >
              <xy-input
                type="textarea"
                v-model="addForm.TechnicalRequirement"
                clearable
              ></xy-input
            ></el-form-item>
            <!-- #endregion -->

            <el-form-item :label="$language.local('入网申请表')">
              <upload-file v-model="addForm.attFile"></upload-file>
            </el-form-item>
          </el-form>
        </el-collapse-item>
        <el-collapse-item name="4">
          <h1 slot="title">资质文件</h1>

          <el-form
            :disabled="isCheck"
            :model="addForm"
            :rules="$rules"
            ref="qualificationFilesRef"
            label-width="11rem"
            label-position="left"
            class="pl-2"
          >
            <el-form-item
              prop="BusinesslicenseImg"
              :label="$language.local('营业执照')"
            >
              <upload-image v-model="addForm.BusinesslicenseImg"></upload-image>
            </el-form-item>
            <!-- 法人身份证（正面） -->
            <el-form-item
              prop="identitycardImg"
              :label="$language.local('identitycardImg')"
            >
              <upload-image v-model="addForm.identitycardImg"></upload-image>
            </el-form-item>
            <!-- 法人身份证（背面） -->
            <el-form-item
              prop="identitycardBackImg"
              :label="$language.local('identitycardBackImg')"
            >
              <upload-image
                v-model="addForm.identitycardBackImg"
              ></upload-image>
            </el-form-item>
          </el-form>
        </el-collapse-item>
      </el-collapse>
      <div class="form-footer mt-1 mb-2">
        <el-button @click="$router.go(-1)">{{
          $language.local("取消")
        }}</el-button>
        <template v-if="action == 'Check'">
          <el-button class="mr3" type="danger" @click="onCheck(2)">{{
            $language.local("不通过")
          }}</el-button>
          <el-button type="success" @click="onCheck(1)">{{
            $language.local("通过")
          }}</el-button>
        </template>
        <el-button v-else type="primary" @click="onSubmit">{{
          $language.local("确定")
        }}</el-button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeNames: ["1"],
      action: "Create",
      apiName: "/api/Merchant/Create",
      addForm: {
        customerName: "",
        customerManager: "",
        AgentId: null,
        customTaxIdcd: "",
        customLegalPerson: "",
        IdNumber: "",
        customCollector: "",
        customCollectorPhone: "",
        customMail: "",
        areaName: "",
        invoiceType: 1,
        empSignType: 1,
        Companytype: 1,
        payType: 1,
        nsrxz: 1,
        backcard: [
          {
            BankNo: "",
            AccountBank: "",
          },
        ],
        BankName: "",
        BankCardNo: "",
        IsSendMessageToEmp: 0,
        BusinessModel: null,
        ProjectName: null,
        TechnicalRequirement: null,
        RequirementDescription: "",
        attFile: "",
        BusinesslicenseImg: "",
        identitycardImg: "",
        identitycardBackImg: "",
        customNature: "",
        customerTelephone: "",
        contractType: null,
        customIndustry: "",
        expectedMonthlyFlow: null,
        contractTplId: null,
        Imgs: null,
        invoiceSubject: "",
        shengcode: "",
        shengname: "",
        shicode: "",
        shiname: "",

        checkPhone: "",

        IsPayNeedCheck: null,
        InviteCode: "",
        IsMana: null,
        customerManagerId: null,
        SignatureRate: null,
        EmpSignatureRate: null,
        registeredcapital: "",
        registereddate: "",
        BusinessScope: null,
        merchantPublicKey: "",
        merchant_number: "",
        originalcompanyId: "",
        wmsignuserId: "",
        sealId: "",
      },
      agents: [],
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
      isCheck: false,
      continueAdd: 0,
      imageUrl: "",
      banks: [],
      attFileList: [],
      BusinesslicenseImgs: [],
      identitycardImgs: [],
      identitycardBackImgs: [],
      user: this.$store.getters.user,
    };
  },
  created() {
    this.onConfig();
    this.getAgents();
    this.getBank();
  },
  methods: {
    async onConfig() {
      let { action, apiName, merchantId } = this.$route.query;
      console.log(action);
      if (!action || !apiName) {
        return;
      }
      if (action == "Check") {
        this.isCheck = true;
      }
      this.apiName = apiName;

      let editMerchant = await this.getMerchant(merchantId);
      console.log(editMerchant);
      if (!editMerchant) {
        console.log(123);
        this.$router.go(-1);
        return;
      }
      // this.addForm = editMerchant;
      this.addForm = {
        ...this.addForm,
        ...editMerchant,
      };
      this.action = action;
      if (this.addForm.attFile) {
        let name = this.addForm.attFile.replace(/.+\//, "");
        console.log(name);
        if (name) {
          this.attFileList = [{ name, url: this.addForm.attFile }];
        }
      }
      let {
        BusinesslicenseImg,
        identitycardImg,
        identitycardBackImg,
      } = this.addForm;
      if (BusinesslicenseImg) {
        let name = BusinesslicenseImg.replace(/.+\//, "");
        if (name) {
          this.BusinesslicenseImgs = [{ name, url: BusinesslicenseImg }];
        }
      }
      if (identitycardImg) {
        let name = identitycardImg.replace(/.+\//, "");
        if (name) {
          this.identitycardImgs = [{ name, url: identitycardImg }];
        }
      }
      if (identitycardBackImg) {
        let name = identitycardBackImg.replace(/.+\//, "");
        if (name) {
          this.identitycardBackImgs = [{ name, url: identitycardBackImg }];
        }
      }
    },
    async getMerchant(id) {
      let response = await this.$http.get(`/api/Merchant/GetModel/${id}`);
      console.log(response);
      return response.data.Data;
    },
    async getAgents() {
      let response = await this.$http.get("/api/Common/GetAgentList");
      console.log(response);
      if (response.data.Code == 200) {
        this.agents = response.data.Data;
      }
    },
    async getBank() {
      let response = await this.$http.get("/api/Common/GetBankItem");
      console.log(response);
      this.banks = response.data.Data;
    },

    async uploadAttachment(e) {
      //   console.log(e);
      const fd = new FormData();
      fd.append("file", e.file);

      let response = await this.$http.upload(e.action, fd);
      console.log(response);
      this.addForm.attFile = response.data.Data.docurl;
      return response;
    },
    async uploadImg(e) {
      console.log(e);
      const fd = new FormData();
      fd.append("file", e.file);
      let response = await this.$http.upload("/api/Common/UploadPhoto", fd);
      console.log(response);
      this.addForm[e.action] = response.data.Data.picurl;
      return response;
    },

    handleSuccess(response, file, fileList) {
      console.log(response);
      console.log(file);
      console.log(fileList);
      console.log(this.BusinesslicenseImgs);
    },
    handleError(response) {
      this.$message.error(response.data.Message);
    },
    handleRemove(file, name) {
      console.log(file);
      console.log(name);
      let arr = this.$refs[name].uploadFiles;
      let index = arr.indexOf(file);
      arr.splice(index, 1);
      // console.log(file, fileList);
      // return this.$confirm(`确定移除 ${file.name}？`);
    },
    removeFile(file, fileList) {
      console.log(file, fileList);
      console.log(this.$refs["filesRef"]);
      let arr = this.$refs["filesRef"].uploadFiles;
      let index = arr.indexOf(file);
      arr.splice(index, 1);
      console.log(this.fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 ${this.$refs["attFile"].limit} 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      console.log(file);
      window.location.href = file.url;
    },
    uploadChange(file, files) {
      console.log(file, files);
      // this.taskInfo.attFile = files;
    },
    handleQualificationFilesChange(res, files) {
      console.log(res);
      console.log(files);
      if (res.status == "ready") {
        // this.qualificationFiles.BusinesslicenseImg = res.url;
        this.continueAdd++;
      }
      console.log(this.fileList);
      // this.qualificationFiles.BusinesslicenseImg = file.url;
      // this.continue = false;
      // this.qualificationFiles.BusinesslicenseImg = URL.createObjectURL(
      //   file.raw
      // );
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAttFileUpload(file) {
      let typeName = file.name.substr(-4);
      let accept = ".doc,.pdf,.xls";
      if (accept.indexOf(typeName) == -1) {
        this.$message.error("请上传文件 格式：.doc.xls.pdf");
        return false;
      }
      // const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 10;

      if (!isLt2M) {
        this.$message.error("上传文件大小不能超过 10MB!");
        return false;
      }
      // return isJPG && isLt2M;
      return true;
    },
    beforeImageUpload(file) {
      console.log(file);
      let typeName = file.name.substr(-4);
      let accept = ".jpg.jpeg.png";
      if (accept.indexOf(typeName) == -1) {
        this.$message.error("请上传文件 格式：.doc.xls.pdf");
        return false;
      }
      // const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 5;

      if (!isLt2M) {
        this.$message.error("上传文件大小不能超过 5MB!");
        return false;
      }
      // return isJPG && isLt2M;
      return true;
    },
    async onCheck(check) {
      let response = await this.$http.post(
        `/api/MerchantCheck/Check/${this.addForm.Id}?CheckStatus=${check}&CheckResult=${check}`
      );
      console.log(response);
      this.$router.replace("/merchantchecklist");
    },
    async onSubmit() {
      this.$refs["company-info"].validate((valided, err1) => {
        if (!valided) {
          let keys = Object.keys(err1);
          this.$message.error(
            this.$language.local(err1[keys[0]][0].field) +
              this.$language.local(err1[keys[0]][0].message)
          );
          return;
        }
        this.$refs["selectForm"].validate((valided, err2) => {
          if (!valided) {
            console.log(err2);
            let keys = Object.keys(err2);
            this.$message.error(
              this.$language.local(err2[keys[0]][0].field.replace(/.+\./, "")) +
                this.$language.local(err2[keys[0]][0].message)
            );
            this.activeNames.push("2");
            return;
          }
          this.$refs["taskInfoRef"].validate(async (valided, err3) => {
            if (!valided) {
              let keys = Object.keys(err3);
              this.$message.error(
                this.$language.local(err3[keys[0]][0].field) +
                  this.$language.local(err3[keys[0]][0].message)
              );
              this.activeNames.push("3");
              return;
            }
            this.$refs["qualificationFilesRef"].validate(
              async (valided, err3) => {
                if (!valided) {
                  let keys = Object.keys(err3);
                  this.$message.error(
                    this.$language.local(err3[keys[0]][0].field) +
                      this.$language.local(err3[keys[0]][0].message)
                  );
                  this.activeNames.push("4");
                  return;
                }
                console.log(this.addForm);
                let query = {
                  AccountName: this.addForm.customerName,
                  AccountBank: this.addForm.backcard[0].AccountBank,
                  BankNo: this.addForm.backcard[0].BankNo,
                };

                await this.$http.post(this.apiName, this.addForm, query);
                this.$router.replace("/merchantlist");
              }
            );
          });
        });
      });
    },
    downloadFile() {
      this.$common.downloadFile({
        url:
          "https://6f6e-online-signing-hvpci-1300843560.tcb.qcloud.la/webfile/%E4%BC%81%E4%B8%9A%E5%85%A5%E7%BD%91%E7%94%B3%E8%AF%B7%E8%A1%A83.4.xls?sign=65a8512a13ea29ce8455e356b6436445&t=1624412529",
      });
    },
  },
};
</script>

<style lang="less" scoped>
.page-footer {
  padding-bottom: 4rem;
}
.add-form {
  display: flex;
  flex-direction: column;
  justify-content: center;
  //   align-items: center;
  margin: 2rem;

  //border: 1px solid #aaa;
}
.company-info-form {
  width: 100%;
}
.el-select {
  width: 100%;
}

.upload-img {
  display: flex;
  flex-direction: column-reverse;
  align-items: flex-start;
  .upload-btn {
    margin: 1rem;
    margin-left: 0;
  }
}
.tips {
  color: gray;
  font-size: 0.8rem;
}
</style>
